package trocabi.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.print.PrintService;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.DialogTypeSelection;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import trocabi.model.Depositaire;
import trocabi.Renderer.BoldCellRenderer;
import trocabi.Renderer.ColorCellRenderer;
import trocabi.Renderer.DefaultCellRenderer;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import trocabi.DAO.DAOArticle;
import trocabi.Socle.SwingTools;
import trocabi.Socle.TechnicalException;
import trocabi.model.Article;
import trocabi.printer.Barcode;
import trocabi.printer.OpenDocTools;
import trocabi.printer.PrintBarcodes;
import trocabi.service.ArticleServices;
import trocabi.service.DepositaireServices;
import trocabi.service.PrinterParameters;
import trocabi.service.PrinterService;

public class GuiDeposerArticles extends JFrame {
    private static final Logger      logger = Logger.getLogger("trocabi.view.GuiDeposerArticles");
    private DAOArticle               daoArticle = DAOArticle.getInstance();
    private ArticleServices          articleServices;
    private Depositaire              depositaire;
    private DepositaireServices      depositaireServices;
    private JTableModelDepotArticles articlesModele;
    private JButton                  btImprimerEtiquette;
    private JButton                  btImprimerEtiquettes;
    private JButton                  btImprimerRecu;
    private JButton                  btAjouter;
    private JButton                  btTerminer;
    private JButton                  btModifier;
    private JButton                  btSupprimer;
    private JPanel                   headerPanelButton;
    private JPanel                   footerPanelButton;
    private JTextField               fieldId;
    private GuiSaisieArticle         guiSaisieArticle;
    private JPanel                   pContentPanel;
    private JPanel                   pCenter;
    private JScrollPane              spListe;
    private JTable                   viewListArticle; 
   

    public GuiDeposerArticles() {
        initComponents();
        articleServices=new ArticleServices();
        depositaireServices=new DepositaireServices();
    }

    private void initComponents() {
        this.setTitle("Dépôt - Gestion des articles déposés");
        this.setSize(632, 632);
        this.setLocationRelativeTo(null);
        this.setResizable(false);
         /*
        this.addComponentListener(new ComponentAdapter() {
            public void componentResized(ComponentEvent e) {
                JFrame me=(JFrame) e.getSource();
                Dimension size=me.getSize();
                // This is only called when the user releases the mouse button.
                System.out.println(String.format("h=%d w=%d",size.height,size.width));
            }
        });
        */
        this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

        // Content panel de type BorderPanel --> nord = titre / centre = contenu / sud = licence, droits, auteurs ...
        pContentPanel = new JPanel(new BorderLayout());
        pContentPanel.setBackground(Color.white);
        this.setContentPane(pContentPanel);

        /*
         * Que du gridBagLayout
         * Panel de 4 lignes --> lignes 2 à 4 contiennent des panels (ligne 3 = scrollpanel / les autres = GridBagLayout)
         */
        pCenter = new JPanel(new GridBagLayout());
        GridBagConstraints grid = new GridBagConstraints();
        // Label Nom, Prénom, ID
        grid.gridx = 0;
        grid.gridy = 0;
        grid.insets = new Insets(10, 10, 10, 0);
        grid.fill = GridBagConstraints.HORIZONTAL;
        grid.anchor = GridBagConstraints.LINE_START;
       
        fieldId = new JTextField();
        fieldId.setEditable(false);
        fieldId.setPreferredSize(new Dimension(150, 20));
        pCenter.add(fieldId, grid);
        // Sous-panel "Rechercher Dépositaire"
        headerPanelButton = new JPanel(new GridBagLayout());
        btAjouter = new JButton("Ajouter");
        btAjouter.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                guiSaisieArticle.clear();
                guiSaisieArticle.setDepositaire(depositaire);
                guiSaisieArticle.setMode(GuiSaisieArticle.Mode.CREATE); 
                guiSaisieArticle.setVisible(true);
            }
        });
        grid.gridx = 0;
        grid.gridy = 0;
        grid.weighty = 0;
        grid.fill = GridBagConstraints.NONE;
        grid.anchor = GridBagConstraints.LINE_START;
        headerPanelButton.add(btAjouter, grid);
        btModifier = new JButton("Modifier");
        btModifier.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                guiSaisieArticle.clear();
                guiSaisieArticle.setDepositaire(depositaire);
                guiSaisieArticle.setArticle(articlesModele.getArticleAt(viewListArticle.getSelectedRow()));
                guiSaisieArticle.setMode(GuiSaisieArticle.Mode.UPDATE); 
                guiSaisieArticle.setVisible(true);
            }
        });
        grid.gridx = 1;
        grid.anchor = GridBagConstraints.LINE_START;
        headerPanelButton.add(btModifier, grid);
        btSupprimer = new JButton("Supprimer");
        btSupprimer.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (viewListArticle.getSelectedRow() != -1) {
                    daoArticle.bDelete(articlesModele.getArticleAt(viewListArticle.getSelectedRow()).getId());
                    articlesModele.remove(articlesModele.getArticleAt(viewListArticle.getSelectedRow()));
                }
            }
        });
        grid.gridx = 2;
        grid.anchor = GridBagConstraints.LINE_START;
        headerPanelButton.add(btSupprimer, grid);
        btImprimerEtiquette = new JButton("Imprimer une étiquette");
        btImprimerEtiquette.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (viewListArticle.getSelectedRow() != -1) {
                    Barcode barecode = new Barcode(articlesModele.getArticleAt(viewListArticle.getSelectedRow()));
                    // List<Barcode> toPrint = new ArrayList<>();
                    // toPrint.add(barecode);
                    // printBarcodes(toPrint);
                    
                    Barcode barcode=new Barcode(articlesModele.getArticleAt(viewListArticle.getSelectedRow()));
                    PrinterService printerService = new PrinterService("testImpression");
                    try {
                        printerService.selectPrinter("Brother QL-700"); // "PDFCreator
                            // printerService.selectPrinter("Samsung SCX-4623 Series"); // "PDFCreator
                            // printerService.selectPrinter("PDFCreator"); // "PDFCreator
                            PrinterParameters param=printerService.getParameters();            
                            // printerService.setMargin(new MediaPrintableArea((float) 1.52,(float)2.96,(float)25.908,(float) 88.90,MediaPrintableArea.MM));
                            printerService.setProperty(new Copies(1));
                            printerService.setProperty(DialogTypeSelection.NATIVE);
                            printerService.setProperty(new Copies(1));
                            // printerService.showPageDialog();
                            printerService.setProperty(printerService.getMargin());
            
            
                            if (printerService.showPrintDialog())  printerService.printImage(barcode.toBufferedImg());
                            //barcode.toBmpFile("c:/temp/img.bmp");
                    } catch (TechnicalException ex) {
                        Logger.getLogger(PrinterService.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (PrinterException ex) {
                         Logger.getLogger(PrinterService.class.getName()).log(Level.SEVERE, null, ex);
                     }   
                    
                }
            }
        });
        grid.gridx = 3;
        grid.weightx = 1;
        grid.insets = new Insets(10, 0, 10, 10);
        grid.anchor = GridBagConstraints.LINE_END;
        headerPanelButton.add(btImprimerEtiquette, grid);
        grid.gridx = 0;
        grid.gridy = 1;
        grid.weighty = 0;
        grid.fill = GridBagConstraints.BOTH;
        pCenter.add(headerPanelButton, grid);
        // Sous-panel "Afficher Résultats Recherche"
        articlesModele = new JTableModelDepotArticles();
        viewListArticle = new JTable(articlesModele);
        viewListArticle.getModel().addTableModelListener(new TableModelListener() {
            @Override
            public void tableChanged(TableModelEvent tme) {
                if (articlesModele.getRowCount() > 0) {
                    btImprimerEtiquettes.setEnabled(true);
                    btImprimerEtiquette.setEnabled(true);
                    btImprimerRecu.setEnabled(true);
                } else {
                    btImprimerEtiquettes.setEnabled(false);
                    btImprimerEtiquette.setEnabled(false);
                    btImprimerRecu.setEnabled(false);
                }
            }
        });
        int[] colSize = { 85, 110, 80, 80, 70, 70, 80 };
        SwingTools.setJTableSize(viewListArticle, colSize);
        viewListArticle.setDefaultRenderer(Object.class, new DefaultCellRenderer());
        viewListArticle.getColumnModel().getColumn(0).setCellRenderer(new BoldCellRenderer());
        viewListArticle.getColumnModel().getColumn(5).setCellRenderer(new ColorCellRenderer());
        viewListArticle.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent lse) {
                if (viewListArticle.getSelectedRowCount() == 1) {
                    btModifier.setEnabled(true);
                    btSupprimer.setEnabled(true);
                    btImprimerEtiquette.setEnabled(true);
                    btImprimerRecu.setEnabled(true);
                } else {
                    btModifier.setEnabled(false);
                    btSupprimer.setEnabled(false);
                    btImprimerEtiquette.setEnabled(false);
                    btImprimerRecu.setEnabled(false);
                }
            }
        });
        viewListArticle.setRowSorter(null); // disable row sorter
        spListe = new JScrollPane(viewListArticle);
        grid.gridx = 0;
        grid.gridy = 2;
        grid.weightx = 0;
        grid.weighty = 1;
        grid.insets = new Insets(0, 10, 0, 10);
        pCenter.add(spListe, grid);
        // Sous-panel "Boutons"
        footerPanelButton = new JPanel(new GridBagLayout());
        btImprimerRecu = new JButton("Imprimer un reçu");
        btImprimerRecu.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {	
                OpenDocTools odt=OpenDocTools.getInstance();
		odt.printRecuDepositaire(articlesModele.getArticles(), depositaire);
            }
        });
        grid.gridx = 0;
        grid.gridy = 0;
        grid.insets = new Insets(10, 10, 10, 0);
        grid.weighty = 0;
        grid.fill = GridBagConstraints.NONE;
        grid.anchor = GridBagConstraints.LINE_START;
        footerPanelButton.add(btImprimerRecu, grid);
        btImprimerEtiquettes = new JButton("Imprimer toutes les étiquettes");
        btImprimerEtiquettes.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                printBarcodes(Barcode.generateBarcodeList(articlesModele.getArticles()));
            }
        });
        grid.gridx = 1;
        grid.anchor = GridBagConstraints.LINE_START;
        footerPanelButton.add(btImprimerEtiquettes, grid);
        btTerminer = new JButton("Terminer");
        btTerminer.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
            }
        });
        grid.gridx = 2;
        grid.weightx = 1;
        grid.insets = new Insets(10, 0, 10, 10);
        grid.anchor = GridBagConstraints.LINE_END;
        footerPanelButton.add(btTerminer, grid);
        grid.gridx = 0;
        grid.gridy = 3;
        grid.fill = GridBagConstraints.HORIZONTAL;
        pCenter.add(footerPanelButton, grid);
        pContentPanel.add(pCenter, BorderLayout.CENTER);
    }

    public void clear() {
        this.setLocationRelativeTo(null);
        btModifier.setEnabled(false);
        btSupprimer.setEnabled(false);
        btImprimerEtiquette.setEnabled(false);
        btImprimerRecu.setEnabled(false);
        btImprimerEtiquettes.setEnabled(false);
        articlesModele.removeAll();
    }

    public void setDepositaire(Depositaire depositaire) throws TechnicalException {
        this.depositaire = depositaire;
        clear();
        fieldId.setText(depositaireServices.idToString(depositaire));
        addArticles(articleServices.searchArticleByStatus(depositaire,Article.Etat.DEPOT));
    }

    public void addArticles(Article article) {
        articlesModele.add(article);
    }
    public void addArticles(ArrayList<Article> articles) {
        articlesModele.add(articles);
    }
   
    public JTable getJTable() {
        return viewListArticle;
    }
 
    public void setGuiSaisieArticle(GuiSaisieArticle guiSaisieArticle) {
        this.guiSaisieArticle=guiSaisieArticle;
    }

    public PrintService getPrinter(String printerName) {
        PrinterJob job = PrinterJob.getPrinterJob();
        PrintService []printers = PrinterJob.lookupPrintServices();
        for (int i=0; i<printers.length;i++) {
            System.out.println("selected printer: " + printers[i]);
            if (printers[i].getName().compareTo(printerName)==0) return printers[i];
        }
        return null;
    }
    
    
    private void printBarcodes(List<Barcode> toprint) {
        // Step 1: Set up initial print settings.
        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
        
        PrintService printer=getPrinter("Brother QL-700"); // TODO; nul case
        PrinterJob job = PrinterJob.getPrinterJob();
        try {
            job.setPrintService(printer); 
            //job.pageDialog(aset);  // Step 2: Pass the settings to a page dialog and print dialog.
            if (job.printDialog(aset)) {
             PrintBarcodes pb = new PrintBarcodes(toprint, job.getPageFormat(aset));
             job.print();
            }
            
        } catch (PrinterException ex) {
            Logger.getLogger(GuiDeposerArticles.class.getName()).log(Level.SEVERE, null, ex);
        }
        /*
        if (services.length > 0) {
             System.out.println("selected printer: " + services[0]);
             try {
        job.setPrintService(service[0]); 
        // Step 2: Pass the settings to a page dialog and print dialog.
        job.pageDialog(aset);
        if (pj.printDialog(aset)) {
                // Step 4: Update the settings made by the user in the dialogs.
                // Step 5: Pass the final settings into the print request.
                pj.print(aset);
        }
        } catch (PrinterException(pe)) {
                System.err.println(pe):
        }
        }
        * */
       // PrintBarcodes pb = new PrintBarcodes(toprint, job.defaultPage());
        // job.setPageable(pb);
        if (job.printDialog() == true) { // TODO: mettre ca en tache de fond
            try {
                 PrintBarcodes pb = new PrintBarcodes(toprint, job.defaultPage());
                 job.setPageable(pb);
                job.print();
            } catch (PrinterException e) {
                logger.severe(String.format("%s %s", e.getLocalizedMessage(), e.getMessage()));
            }
        }
    }
}
